/****************************************************************
 ** Product  :   HP Subscriber Network Application Policy
 ** Module   :   gr-manager
 ** Date: Apr 10, 2015               
 ** Author: Chen Zhenhua
 ** (C) Copyright 2015, Hewlett-Packard Company, All Rights Reserved.
 ** This software is the proprietary information of HP, Inc.  
 ** Use is subject to license terms.
 *****************************************************************
 ** Description:   
 **   Get the SGM status.
 **    
 ****************************************************************/
package com.hp.snap.gr.action.impl;

import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.jaxb.ActionType;
import com.hp.snap.gr.model.jaxb.GeneralActionType;
import com.hp.snap.gr.model.jaxb.ParameterType;
import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.SSHTools;
import com.hp.snap.gr.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

/**
 * Get local site or remote site SGM status, which can be specified with
 * the remote parameter in the action configuration, and the SGM status save into action output to pass it
 * next action to handle.
 * 
 * 
 * There are one parameter can be configured in the action, Shell.
 * 
 * Remote: is remote or local SGM, optional value: true or false.
 * 
 * Action output: 
 *    REMOTE_SGM_STATUS: put the remote SGM status into output.
 *    LOCAL_SGM_STATUS:  put the local SGM status into output.
 * 
 * <P>
 * Version: 3.3 <br>
 * Author: Chen Zhenhua Date: Apr 10, 2015
 * 
 * </P>
 * 
 **/
public class GetSGMStatusActionHandler extends AbstractActionHandler {

    private final static String GR_STATUS_FILE_PREFIX = ".SNAP-GR-Status.";
    private static Logger logger = LoggerFactory.getLogger(GetSGMStatusActionHandler.class);

    @Override
    public void execute(ActionType action,
                        Map<String, Object> actionPlanInputs,
                        Map<String, Object> actionPlanOutputs) throws ActionException {

        GeneralActionType actionType = (GeneralActionType) action;
        List<ParameterType> parameterTypes = actionType.getParameter();
        Map<String, String> parameterMap = Utils.contructParamMap(parameterTypes);
        boolean remote = parameterMap.get("Remote") != null && Boolean.parseBoolean(parameterMap.get("Remote"));


        String runSiteName = Utils.getConfigurationValue(Constants.CFG_GRL_DEPLOY_NAME);
        if (remote)
            runSiteName = Utils.getCorrespondSiteName(runSiteName);
        //String sshPath = Constants.SSH_PATH;
        String _sshUser = Utils.getConfigurationValue(Constants.CFG_GRG_ROOT + "/" + runSiteName, Constants.CFG_GRG_SITE_SSH_USER);
        String _keyFile = Constants.SSH_PATH + File.separator + Constants.SSH_KEY_FILE;
        String _hostIP = Utils.getGRHostIP(runSiteName);
        String _grStatusFilePath = Constants.USER_HOME + File.separator + "GR";
        SSHTools ssh = new SSHTools(_sshUser, _keyFile);
        String result = "";
        try {
            result = ssh.cmd(_hostIP, "ls -alt " + _grStatusFilePath);
            //.cmd(_host, command);
        } catch (Exception e) {
            // e.printStackTrace();
            logger.error(e.toString());
        }
        int status = ssh.getExitStatusOfCommandResult(result);
        if (logger.isDebugEnabled()) {
            logger.debug("execute getting remote SGM status command status is:{}", status);
        }
        String resultStr = ssh.getCommandOutput(result);
        String stats = "STOPPED";
        try {
            LineNumberReader r = new LineNumberReader(new StringReader(resultStr));
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                int index = line.indexOf(GR_STATUS_FILE_PREFIX);
                if (index >= 0) {
                    String filename = line.substring(index);
                    stats = filename.replace(GR_STATUS_FILE_PREFIX, "").toUpperCase();
                    break;
                }
            }
        } catch (IOException e) {
            throw new ActionException("read the remote SGM status failed!", e.getCause());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("getting the remote SGM status is:{}", stats);
        }
        ssh.closeAll();
        if (remote)
            actionPlanOutputs.put(Constants.STATUS_REMOTE_SGM, stats);
        else
            actionPlanOutputs.put(Constants.STATUS_LOCAL_SGM, stats);
    }

}
